using FluentSqlKata;
using Microsoft.AspNetCore.Mvc;
using SqlKata.Execution;
using SqlKataDemo.WebApi.Models;

namespace SqlKataDemo.WebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly QueryFactory _queryFactory;

        public ProductController(QueryFactory queryFactory, ILogger<ProductController> logger)
        {
            queryFactory.Logger = result =>
            {
                logger.LogError(result.Sql);
            };
            _queryFactory = queryFactory;
        }

        [HttpGet]
        public Order Get()
        {
            var order = new Order();
            var product = new Product();

            var query = FluentQuery.Query()
                .From(() => order)
                .Join(() => product, () => product.Id, () => order.ProductId)
                .Select("name", () => order.Name);

            order = _queryFactory.Get<Order>(query).FirstOrDefault();
            return order;
        }
    }
}